/*
 * Copyright Owen Watson 2009
 * 
 * This file is part of ArtNotes.
 *
 * ArtNotes is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * ArtNotes is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with ArtNotes.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.CoreGraphics;
using FlickrNet;
using System.Net;
using System.Threading;

namespace ArtNotes
{

	/// <summary>
	/// Shows the results of a flickr image search in
	/// groups of 9 images per 'page'.
	/// Selecting an Image will show a larger image
	/// and the images description.
	/// </summary>
	public class ANFlickrResults : UIViewController
	{

		private bool returnFromImage;
		private UIActivityIndicatorView progressIndicator;
		private UILabel loadingMsg;
		private string searchTerm;
		
		public ANFlickrResults (string searchTerm)
		{
			this.searchTerm = searchTerm;
		}
		
		public override void ViewDidLoad ()
		{
			this.View.Frame = new RectangleF(0,0,320,370);
			this.View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromFile("Images/notepaper.png"));
			
			this.Title = "Results";
			returnFromImage = false;
			//base.ViewDidLoad ();
		}
		
		// taken from monotouch samples
		private UIActivityIndicatorView ProgressIndicator ()
		{
			UIActivityIndicatorView pind = new UIActivityIndicatorView (new RectangleF (145f, 165f, 30f, 30f)){
				ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray,
				AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin |
					UIViewAutoresizing.FlexibleRightMargin |
					UIViewAutoresizing.FlexibleTopMargin |
					UIViewAutoresizing.FlexibleBottomMargin,
				Tag = 1
			};
	
			//pind.StartAnimating ();
			//pind.SizeToFit ();
			
			return pind;
		}
		
		public override void ViewWillAppear (bool animated)
		{
			if(!returnFromImage)
			{
				loadingMsg = new UILabel(new RectangleF(50,130,200,25));
				loadingMsg.Text = "Loading Search Results...";
				loadingMsg.Font = UIFont.FromName ("Marker Felt", 18);
				loadingMsg.BackgroundColor = UIColor.Clear;
				this.View.AddSubview(loadingMsg);
							
				progressIndicator = ProgressIndicator();
				progressIndicator.HidesWhenStopped = true;
				progressIndicator.StartAnimating();
				
				this.View.AddSubview(progressIndicator);
				
				UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
			}
			
			UIImageView leftArrow = new UIImageView(new RectangleF(30,330,30,30));
			UIImageView rightArrow = new UIImageView(new RectangleF(260,330,30,30));
			
			leftArrow.Image = UIImage.FromFileUncached("Images/arrow_back.png");
			rightArrow.Image = UIImage.FromFileUncached("Images/arrow_forward.png");
			
			this.View.AddSubview(rightArrow);
			this.View.AddSubview(leftArrow);
		}

		private UIButton ImageButtonType (RectangleF frame, UIImage defaultImage, UIImage pressedImage)
		{
			var background = defaultImage;//UIImage.FromFile("Images/btnSearch.png");
			var backgroundPressed = pressedImage;//UIImage.FromFile("Images/btnSearchPressed.png");
			//var frame = frame;
			
			var button = new UIButton(frame);
			var nbackground = background.StretchableImage(12,0);
			var nbackgroundPressed = backgroundPressed.StretchableImage(12,0);
			button.SetBackgroundImage(nbackground,UIControlState.Normal);
			button.SetBackgroundImage(nbackgroundPressed,UIControlState.Highlighted);

			button.Tag = 1;
			return button;
		}
		
		struct FlickrPhotoPreview
		{
			public Photo photo;
			public UIButton Image;
			//public ANFlickrImage anFlickrImage;

			public FlickrPhotoPreview (Photo photo, UIButton image)//, ANFlickrImage anFlickrImage)
			{
				this.photo = photo;
				this.Image = image;
				//this.anFlickrImage = anFlickrImage;
			}
		}
		
		FlickrPhotoPreview[] flickrPhotoPreviews;
		//UIButton[] flickrPhotoPreviews;
		
		public override void ViewDidAppear (bool animated)
		{
			if(!returnFromImage)
			{
				try
				{
					//string apikey = AN_APP_OPTIONS.AN_FLICKR_APIKEY;
					//string secret = AN_APP_OPTIONS.AN_FLICKR_SECRET;
					string frob = "";
					string authUrl = "";
					
					//Flickr flickr = new Flickr();
					//flickr.ApiKey = apikey;
					
					Flickr flickr = AN_APP_OPTIONS.AN_FLICKR;
					
					PhotoSearchOptions searchOptions = new PhotoSearchOptions();
					searchOptions.Tags = searchTerm;
					searchOptions.PerPage = 9;
					
					Photos foundPhotos = flickr.PhotosSearch(searchOptions);
					
					Console.WriteLine("Total pictures: " + foundPhotos.TotalPhotos.ToString());
					
					PhotoCollection foundPhotoCollection = foundPhotos.PhotoCollection;			
		
					String docdir = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
					
					//flickrPhotos = new CustomUIImageView[9];
					
					flickrPhotoPreviews = new FlickrPhotoPreview[9];
					
					int x = 0;
					int y = 0;
					int i = 0;
					foreach (Photo p in foundPhotoCollection)
					{
						flickrPhotoPreviews[i].photo = p;
						
						Console.WriteLine("Photo title is " + p.Title);
						Console.WriteLine("Photo URL is " + p.SmallUrl);
						//UIImage tmp = downloadImage(p.ThumbnailUrl, p.PhotoId + ".jpg");
						UIImage tmp = UIImage.FromFile("Images/blank.png");
						//UIImage tmp = UIImage.FromFileUncached(docdir + "/" + p.PhotoId + ".jpg");
						
						flickrPhotoPreviews[i].Image = ImageButtonType(new RectangleF(5 + (x*105),5 + (y*105),100,100), tmp, tmp);
						
						//flickrPhotos[i].UserInteractionEnabled = true;
						
						//flickrPhotos[i].FlickrImage = p;
						
						//Photo ph = flickrPhotoPreviews[i].photo;
						ANFlickrImage anFlickrImage = new ANFlickrImage(p);
						
						flickrPhotoPreviews[i].Image.TouchDown += delegate {
							Console.WriteLine("Image Pressed");
							this.NavigationController.PushViewController(anFlickrImage,true);
							returnFromImage = true;
						};
						
						flickrPhotoPreviews[i].Image.SetTitle(p.LargeUrl,UIControlState.Normal);
						GetImage(flickrPhotoPreviews[i].Image);
						
						this.View.AddSubview(flickrPhotoPreviews[i].Image);
						i++;
						
						if(x < 2)
							x++;
						else
						{
							x = 0;
							y++;
						}
					}
					
					UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
					progressIndicator.StopAnimating();
					loadingMsg.Hidden = true;
				}
				catch(Exception e)
				{
					UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
					progressIndicator.StopAnimating();
					loadingMsg.Hidden = true;
					UILabel noNetworkLabel = new UILabel(new RectangleF(50,130,200,25));
					noNetworkLabel.Font = UIFont.FromName ("Marker Felt", 16);
					noNetworkLabel.BackgroundColor = UIColor.Clear;
					noNetworkLabel.Text = "Error Connecting to Flickr!";
				}
			}
			else
				returnFromImage = false;
		
		}

		// Adaoted from here...
		// http://simon.nureality.ca/?p=211
		// ...
		// Leaks Memory!
		private void GetImage(UIButton controller)
		{
		    controller.ImageView.Alpha = 0.0f;
		    //if (story.Thumbnail != null && story.Thumbnail.Src != string.Empty)
		    //{
		       // if (images.ContainsKey(story.Thumbnail.Src) == true)
		      //  {
		      //      UIImage imageThumbnail = images[story.Thumbnail.Src];
		      //      controller.ImageThumbnail.Image = imageThumbnail;
		      //      controller.ImageThumbnail.Alpha = 1.0f;
		       // }
		      //  else
		      //  {
		            //controller.ImageUri = story.Thumbnail.Src;
		            ThreadPool.QueueUserWorkItem(RequestImage, controller);
		      //  }
		   // }
		}
		
		// ...now it doesn't leak memory...
		private void RequestImage(object state)
		{		
			using (NSAutoreleasePool pool = new NSAutoreleasePool ()) {
			    UIButton controller = state as UIButton;
			    if (controller != null)
			    {
			        NSUrl imageUrl = NSUrl.FromString(controller.Title(UIControlState.Normal));
			        NSData imageData = NSData.FromUrl(imageUrl);
			        UIImage img = UIImage.LoadFromData(imageData);
			 
					controller.SetBackgroundImage(img,UIControlState.Normal);
					controller.SetBackgroundImage(img,UIControlState.Highlighted);
			        //images.Add(controller.ImageUri, controller.ImageThumbnail.Image);
			 
			        InvokeOnMainThread(delegate { RefreshImage(controller); });
			    }
			}
		}
		 
		private void RefreshImage(UIButton controller)
		{
		    UIView.BeginAnimations("imageThumbnailTransitionIn");
		    UIView.SetAnimationDuration(0.5f);
		    controller.ImageView.Alpha = 1.0f;
		    UIView.CommitAnimations();
		}
		
		public UIImage downloadImage (string url, string filename)
		{
			String docdir = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
			WebClient wc = new WebClient ();
			wc.DownloadFile (url, docdir + "/" + filename);
			UIImage tmp = UIImage.FromFileUncached(docdir + "/" + filename);
			return tmp;
		}

	}
	
	/*public class CustomUIImageView : UIImageView
	{
		public CustomUIImageView ( RectangleF frame )
		{
			this.Frame = frame;
		}
		
		private Photo flickrImage;
		
		public Photo FlickrImage
		{
			get {
				return flickrImage;
			}
			
			set{
				flickrImage = value;
			}
		}
		
		public override void TouchesBegan (MonoTouch.Foundation.NSSet touches, MonoTouch.UIKit.UIEvent e)  
		{  
			Console.WriteLine("touched");
		}
	}*/
}
